package com.neolix.watch.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;


import com.neolix.watch.weather.UpdateLocationTask;

import org.joda.time.DateTime;

import static android.app.AlarmManager.*;
import static android.app.PendingIntent.FLAG_UPDATE_CURRENT;
import static android.content.Context.ALARM_SERVICE;
import static android.content.Context.POWER_SERVICE;
import static android.os.PowerManager.PARTIAL_WAKE_LOCK;
import static com.neolix.watch.util.Constant.UPDATE_WEATHER_INTERVAL_MILLIS;

public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
    private static final int RIGHT_NOW = 0;

    public static void enableAlarm(Context context) {
        AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        am.setRepeating(RTC_WAKEUP, RIGHT_NOW, UPDATE_WEATHER_INTERVAL_MILLIS, getPendingIntent(context));
    }

    public static void cancelAlarm(Context context) {
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        alarmManager.cancel(getPendingIntent(context));
    }

    private static PendingIntent getPendingIntent(Context context) {
        Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
        return PendingIntent.getBroadcast(context, 0, intent, FLAG_UPDATE_CURRENT);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("BaiduLocationApiDem", "定时器启动" + DateTime.now());
        PowerManager pm = (PowerManager) context.getSystemService(POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PARTIAL_WAKE_LOCK, AlarmManagerBroadcastReceiver.class.getName());
        try {
            wl.acquire();
            BackgroundTaskService.submitTask(context, UpdateLocationTask.class);
        } finally {
            wl.release();
        }
    }
}
